package com.study.suanfa.hash;

/**
 * @description: HashTableTest   Hash表，也叫散列表
 * @date: 2020/12/3 13:16
 * @author: hcm
 * @version: 1.0
 */
public class HashTableTest {
    public static void main(String[] args) {
        MyHashTable myHashTable = new MyHashTable(10);
        Emp emp = new Emp(1,"张三");
        Emp emp1 = new Emp(2,"张三");
        Emp emp2 = new Emp(3,"张三");
        Emp emp3 = new Emp(4,"张三");

        myHashTable.add(emp);
        myHashTable.list();
    }
}

/**
 * 创建hash表
 */
class MyHashTable{
    private  EmpLinkedList[] empLinkedLists;
    /**
     * 表示由多少条链表
     */
    private int size;

    public MyHashTable(int size) {
        this.size = size;
        this.empLinkedLists = new EmpLinkedList[size];
        for (int i = 0; i < size; i++) {
            empLinkedLists[i] = new EmpLinkedList();
        }
    }

    /**
     * 遍历链表
     */
    public void list(){
        for (int i = 0; i < size; i++) {
            empLinkedLists[i].list(i);
        }
    }
    /**
     * 添加
     * @param emp
     */
    public void add(Emp emp){
        int eln = hashFun(emp.id);
        empLinkedLists[eln].add(emp);
    }

    /**
     * 散列函数
     */
    public int hashFun(int id){
        return id%size;
    }

}

/**
 * 创建EmpLinkedList 表示链表
 */
class EmpLinkedList{
    /**
     * 头指针指向第一个Emp,头节点指向第一个
     */
    private  Emp head;

    //添加
    public void add(Emp emp){
        if(head == null){
            head = emp;
            return;
        }
        //不是第一个，辅助指针
        Emp curEmp = head;
        while (true){
            if(curEmp.next == null){
                break;
            }
            curEmp = curEmp.next;
        }
        curEmp.next = emp;
    }
    //遍历链表的雇员信息
    public void list(int no){
        if(head == null){
            System.out.println("当前链表为空");
            return;
        }
        Emp curEmp = head;
        while (true){
            System.out.println(no+"条链表信息为:"+curEmp.name);
            if(curEmp.next == null){
                break;
            }
            curEmp = curEmp.next;
        }
    }
}

/**
 * 雇员类
 */
class Emp{
    public Integer id;
    public String name;
    public Emp next;

    public Emp(Integer id, String name) {
        this.id = id;
        this.name = name;
    }
}
